<template>
  <div class="container">

    <a-collapse class="data_list" v-model:activeKey="activeKey">
      <template #expandIcon>
        <DatabaseOutlined />
      </template>
      <a-collapse-panel key="1" header="数据">
        <template #extra>
          <MenuOutlined />
        </template>
        <div style="margin-top: 15px; height: calc(100vh - 245px); overflow-y: auto">
          <a-radio-group v-model:value="layer_selected" v-for="item in dataList" :key="item.code">
            <a-radio :style="radioStyle" :value="item.code" @click="show_layer(item.code)">{{ item.name }}</a-radio>
          </a-radio-group>
        </div>
      </a-collapse-panel>
    </a-collapse>

    <div id="map" style="height: 100%;outline: none;width: 100%;z-index: 0">
    </div>

    <div v-if="lat" class="latlng">经度{{ lng }}，纬度{{ lat }}</div>
    <edit ref="refEdit" :type="type" :typeId="typeId"></edit>
  </div>
</template>

<script>
export default {
  name: "map",
};
</script>
<script setup>
import { onMounted, ref, reactive, nextTick } from 'vue';
import * as L from 'leaflet';
import 'leaflet.wms/dist/leaflet.wms.js'
import 'leaflet/dist/leaflet.css';
import { configList } from "@api/config.js";
import {
  DatabaseOutlined,
  MenuOutlined,
} from '@ant-design/icons-vue'
import * as WMS from "leaflet.wms";
import { getDataList } from "@api/data.js";
import edit from './edit.vue';

const activeKey = ref(['1'])
const layer_selected = ref('')
const radioStyle = reactive({
  display: 'block',
  height: '30px',
  lineHeight: '30px',
});


let lat = ref()
let lng = ref()
let map;
const data_type = ref()
const dataList = ref([])
const map_layers = ref([])
const refEdit = ref(null)
const type = ref()
const typeId = ref()

const DataSource = WMS.Source.extend({
  'showFeatureInfo': function (latlng, info) {
    if (!this._map) {
      return;
    }
    if (!info) {
      return;
    }


    let data = JSON.parse(info);
    if (data.features.length === 0) {
      return;
    }
    let item = data.features[0].properties;

    let html =
      '<table style="width: 90%;"> ' +
      '<tbody> ';
    for (var key in item) {
      if (key === 'created_time') {
        continue;
      }
      if (key === 'updated_time') {
        continue;
      }
      if (key === 'photos') {
        continue;
      }
      if (item[key] == null) {
        item[key] = ''
      }
      let field = data_type.value[key]
      if (field) {
        let label = field.label
        html += '<tr class="tr">' +
          '<td style="width: 50%;text-align: center;">' + label + '</td>' +
          '<td style="width: 50%;text-align: center">' + item[key] + '</td>' +
          '</tr>';
      }
    }
    html += '</tbody></table>';
    html += `<div style="width: 100%;height: 50px"><span class="edit">编辑</span></div>`

    this._map.openPopup(html, latlng, { minWidth: 300, maxHeight: 320 });
    document.getElementsByClassName('edit')[0].onclick = function () {
      refEdit.value.editShowModal = true
      type.value = JSON.parse(info).features[0].id.split('_')[1].split('.')[0]
      typeId.value = JSON.parse(info).features[0].id.split('_')[1].split('.')[1]
      console.log(type.value,typeId.value)
      refEdit.value.handleEdit()
    }
  }

})

const data_source = new DataSource("http://192.168.0.250:8888/geoserver/data/wms",
  {
    format: 'image/png',
    transparent: true,
    zIndex: 999,
    info_format: 'application/json',
  })


function initMap() {
  const TianDiTu = {
    Normal: {
      Map: "https://t{s}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=efcf2d992e8f1c26614a9c1c1aa05e6d",
      Annotion: "https://t{s}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=efcf2d992e8f1c26614a9c1c1aa05e6d",
    },
    Satellite: {
      Map: "https://t{s}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=efcf2d992e8f1c26614a9c1c1aa05e6d",
      Annotion: "https://t{s}.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=efcf2d992e8f1c26614a9c1c1aa05e6d",
    },
    DiXing: {
      Map: "https://t{s}.tianditu.gov.cn/ter_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ter&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=efcf2d992e8f1c26614a9c1c1aa05e6d",
      Annotion: "https://t{s}.tianditu.gov.cn/cta_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cta&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=efcf2d992e8f1c26614a9c1c1aa05e6d",
    },
    Subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
  }
  const GuGe = {
    Normal: {
      Map: "https://gac-geo.googlecnapps.cn/maps/vt?lyrs=m@189&gl=cn&x={x}&y={y}&z={z}",
    },
    Satellite: {
      Map: "https://gac-geo.googlecnapps.cn/maps/vt?lyrs=s&gl=cn&x={x}&y={y}&z={z}",
      Annotion: "https://gac-geo.googlecnapps.cn/maps/vt?lyrs=h@189&gl=cn&x={x}&y={y}&z={z}&scale=2&s=",
    },
    DiXing: {
      Map: "https://gac-geo.googlecnapps.cn/maps/vt?lyrs=t@132,r@292000000&hl=zh-CN&gl=cn&src=app&x={x}&y={y}&z={z}&scale=2&s=Gal",
    },
    Subdomains: [],
  }
  const GaoDe = {
    Normal: {
      Map: "http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
    },
    Satellite: {
      Map: "http://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
      Annotion: "https://gac-geo.googlecnapps.cn/maps/vt?lyrs=h@189&gl=cn&x={x}&y={y}&z={z}&scale=2&s=",
    },
    Subdomains: ["1", "2", "3", "4"]
  }
  const Arcgis = {
    Normal: {
      Map: "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}",
    },
    Satellite: {
      Map: "http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
      Annotion: "https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}",
    },
    DiXing: {
      Map: "https://services.arcgisonline.com/arcgis/rest/services/Elevation/World_Hillshade/MapServer/tile/{z}/{y}/{x}",
    },
    Subdomains: []
  }
  const DiXing = {
    ZaiXian: { Map: "https://b.tile.thunderforest.com/cycle/{z}/{x}/{y}.png?apikey=a5dd6a2f1c934394bce6b0fb077203eb", },
    Subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
  }
  const tianditu_normal = L.layerGroup([L.tileLayer(TianDiTu.Normal.Map, { subdomains: TianDiTu.Subdomains }), L.tileLayer(TianDiTu.Normal.Annotion, { subdomains: TianDiTu.Subdomains })], { zIndex: 1 }),
    tianditu_satellite = L.layerGroup([L.tileLayer(TianDiTu.Satellite.Map, { subdomains: TianDiTu.Subdomains }), L.tileLayer(TianDiTu.Satellite.Annotion, { subdomains: TianDiTu.Subdomains })], { zIndex: 1 }),
    tianditu_dixing = L.layerGroup([L.tileLayer(TianDiTu.DiXing.Map, { subdomains: TianDiTu.Subdomains }), L.tileLayer(TianDiTu.DiXing.Annotion, { subdomains: TianDiTu.Subdomains })], { zIndex: 1 }),
    guge_normal = L.tileLayer(GuGe.Normal.Map, { subdomains: GuGe.Subdomains }, { zIndex: 1 }),
    guge_satellite = L.layerGroup([L.tileLayer(GuGe.Satellite.Map, { subdomains: GuGe.Subdomains }), L.tileLayer(GuGe.Satellite.Annotion, { subdomains: GuGe.Subdomains })], { zIndex: 1 }),
    guge_dixing = L.tileLayer(GuGe.DiXing.Map, { subdomains: GuGe.Subdomains }, { zIndex: 1 }),
    gaode_normal = L.tileLayer(GaoDe.Normal.Map, { subdomains: GaoDe.Subdomains }, { zIndex: 1 }),
    gaode_satellite = L.layerGroup([L.tileLayer(GaoDe.Satellite.Map, { subdomains: GaoDe.Subdomains }), L.tileLayer(GaoDe.Satellite.Annotion, { subdomains: GaoDe.Subdomains })], { zIndex: 1 }),
    arcgis_normal = L.tileLayer(Arcgis.Normal.Map, { subdomains: Arcgis.Subdomains }, { zIndex: 1 }),
    arcgis_satellite = L.tileLayer(Arcgis.Satellite.Map, { subdomains: Arcgis.Subdomains }, { zIndex: 1 }),
    arcgis_dixing = L.tileLayer(Arcgis.DiXing.Map, { subdomains: DiXing.Subdomains }, { zIndex: 1 }),
    zaixian_dixing = L.tileLayer(DiXing.ZaiXian.Map, { subdomains: DiXing.Subdomains }, { zIndex: 1 });

  const baseLayers = {
    "天地图(街道)": tianditu_normal,
    "天地图(卫星)": tianditu_satellite,
    "天地图(地形)": tianditu_dixing,
    "谷歌(街道)": guge_normal,
    "谷歌(卫星)": guge_satellite,
    "谷歌(地形)": guge_dixing,
    "高德(街道)": gaode_normal,
    "高德(卫星)": gaode_satellite,
    "Arcgis(街道)": arcgis_normal,
    "Arcgis(卫星)": arcgis_satellite,
    "Arcgis(地形)": arcgis_dixing,
    "地形(在线)": zaixian_dixing,
  }
  map = L.map("map", {
    center: [34.59, 106.29],
    zoom: 5,
    zoomControl: false,
    layers: [tianditu_normal],
    minZoom: 4,
    attributionControl: false,
  })
  L.control.layers(null, baseLayers, { position: 'topright', autoZIndex: false }).addTo(map);

  map.on('mousemove', function (e) {
    lat.value = e.latlng.lat.toFixed(5)
    lng.value = e.latlng.lng.toFixed(5);
  })
  configList({ all: true }).then(res => {
    dataList.value = res.data
  })


  data_source.addTo(map)

}

function show_layer(code) {
  map.closePopup()

  getDataList(code, 'OPTIONS', {}).then(res => {
    data_type.value = res.data.fields;
  })

  map_layers.value.forEach(v => {
    data_source.removeSubLayer(v)
  })

  if (code === layer_selected.value) {
    layer_selected.value = ''
  } else {
    data_source.addSubLayer(`data:data_${code}`);
    map_layers.value.push(`data:data_${code}`)
  }

}

onMounted(() => {
  initMap()
})
</script>

<style lang="less" scoped>
.container {
  height: calc(100vh - 65px);
}

:deep(.ant-collapse > .ant-collapse-item > .ant-collapse-header) {
  color: #fff;
}

.data_list {
  position: absolute;
  background: #001529;
  backdrop-filter: blur(5px);
  box-shadow: 4px 4px 8px #1890ff;
  z-index: 2;
  margin-top: 20px;
  left: 275px;
  width: 285px;
  border: 1px solid #1afee5;
}

.latlng {
  position: absolute;
  width: 165px;
  height: 18px;
  bottom: 15px;
  background-color: #ffffff;
  right: 15px;
  z-index: 999;
  color: rgb(0, 0, 0);
  text-align: center;
  font-size: 12px;
}

::v-deep .tr:nth-child(odd) {
  background-color: #dddde2;
  height: 30px;
}

::v-deep .tr:nth-child(2n) {
  background-color: #ebebeb;
  height: 30px;
}

::v-deep .edit {
  display: inline-block;
  width: 60px;
  height: 30px;
  text-align: center;
  border: 1px solid rgb(216, 215, 215);
  cursor: pointer;
  margin-left: 199px;
  line-height: 30px;
  margin-top: 10px;

  &:hover {
    color: #1890ff;
    transition: .3s linear;
    box-shadow: 0 0 1px .1px #1890ff;
  }
}
</style>